package com.huakai.springenv.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@RestController
public class SseController {

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream() {
        SseEmitter emitter = new SseEmitter();
        new Thread(() -> {
            try {
                // 模拟服务器推送数据
                for (int i = 0; i < 10; i++) {
                    emitter.send("message " + i);
                    Thread.sleep(1000); // 每秒推送一次
                }
                emitter.complete(); // 完成后关闭连接
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}
